<template>
  <div class="auth">
    <h2>登录</h2>
    <form @submit.prevent="login">
      <input v-model="email" placeholder="邮箱" type="email" required />
      <input v-model="password" placeholder="密码" type="password" required />
      <button type="submit">登录</button>
    </form>

    <p style="margin-top: 10px">
      还没有账号？
      <router-link to="/register">注册</router-link>
    </p>

    <p v-if="error" style="color:red">{{ error }}</p>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import authApi from '../api/auth'
import { useRouter } from 'vue-router'

const email = ref('')
const password = ref('')
const error = ref('')
const router = useRouter()

const login = async () => {
  try {
    const res = await authApi.login({ email: email.value, password: password.value })
    localStorage.setItem('token', res.data.token)
    router.push('/')
  } catch (err) {
    error.value = err.response?.data?.message || '登录失败'
  }
}
</script>

<style>
.auth {
  max-width: 300px;
  margin: 100px auto;
  display: flex;
  flex-direction: column;
}
.auth input, button {
  margin-top: 10px;
  padding: 8px;
}
</style>
